#define _CRT_SECURE_NO_WARNINGS 1
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
unordered_map<int, int> mp;
class Solution {
public:
    TreeNode* mybuilt(vector<int>& inorder, vector<int>& postorder, unordered_map<int, int>& mp, int il, int ir, int pl, int pr) {
        if (il > ir || pl > pr)return nullptr;
        int root_pp = pr;
        int root_pi = mp[postorder[pr]];
        TreeNode* root = new TreeNode(postorder[pr]);
        int lsz = root_pi - il;
        root->left = mybuilt(inorder, postorder, mp, root_pi - lsz, root_pi - 1, pl, pl + lsz - 1);
        root->right = mybuilt(inorder, postorder, mp, root_pi + 1, ir, pl + lsz, pr - 1);
        return root;
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        int n = inorder.size();
        for (int i = 0; i < n; i++) {
            mp[inorder[i]] = i;
        }
        return mybuilt(inorder, postorder, mp, 0, n - 1, 0, n - 1);

    }
};